package cn.source.web.controller.api;

import cn.hutool.http.HttpUtil;
import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.redis.RedisCache;
import cn.source.common.utils.StringUtils;
import cn.source.common.utils.http.HttpUtils;
import cn.source.system.utils.WxUtil;
import cn.source.web.controller.constant.EventConstant;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static cn.source.system.utils.WxUtil.obtainAccessToken;

@RestController
@RequestMapping("/api/wechat")
public class WechatShareController extends BaseController {


    @Resource
    private RedisCache redisCache;

    @Value("${wechat.mp.appId}")
    private String APPID;

    @Value("${wechat.mp.secret}")
    private String SECRET;

    //微信公众号的key
    @Value("${wechat.mp.accessTokenKey}")
    private String accessTokenKey;


    @GetMapping("/shareConfig")
    public AjaxResult getShareConfig(@RequestParam("url") String url) {
        try {
            String accessToken = WxUtil.obtainAccessToken(APPID, SECRET);
            logger.info("accessToken: {}", accessToken);

            Object jsapi_ticket = getJsapiTicket(accessToken);
            logger.info("jsapi_ticket: {}", jsapi_ticket);
            Map<String, String> ret = sign(jsapi_ticket.toString(), url);
            return AjaxResult.success("操作成功", ret);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }

    //获取jsapi_ticket
    public Object getJsapiTicket(String accessToken) {
        Object jsApiTicket = redisCache.getCacheObject(accessTokenKey);
        logger.info("redis 缓存的jsApiTicket: {}",jsApiTicket);
        if(StringUtils.isNull(jsApiTicket) || jsApiTicket.equals("null")){
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
            JSONObject httpObject = JSON.parseObject(HttpUtil.get(url));
            logger.info("httpObject: {}",httpObject);
            if (httpObject.getInteger("errcode") == 0) {
                jsApiTicket = httpObject.getString("ticket");
                Integer expiresTime = httpObject.getInteger("expires_in");

                redisCache.setCacheObject(EventConstant.JSAPI_TICKET, jsApiTicket, expiresTime, TimeUnit.MINUTES);
            } else {
//                throw new Exception("获取jsapi_ticket失败");
            }
        }
        logger.info("jsApiTicket: {}",jsApiTicket);
        return jsApiTicket;

    }

//    // 获取微信公众号的AccessToken
//    private String getMpAccessToken() {
//        Object token = redisCache.getCacheObject(accessTokenKey);
//        if (StringUtils.isNull(token) || token.equals("null")) {
//            token = obtainAccessToken(APPID, SECRET);
//            redisCache.setCacheObject(accessTokenKey, token, 30, TimeUnit.MINUTES);
//        }
//        return token.toString();
//    }


    private static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
